import { existsSync, mkdirSync } from "fs"
import { ifLoggerKeeper } from "./base";
import { HashMap, Util } from "../lib/Util";
import { LocalDate } from "../lib/Time";

export type ALiSLSParams = { accessKeyId: string, secretAccessKey: string, endpoint: string, apiVersion: string }

export class TaoBaoLogger implements ifLoggerKeeper {
    private _catch: HashMap<any> = new HashMap();
    private handle: { stop: any; } | undefined;
    private SLS: any;
    private open: boolean = false;
    name = "taobao"
    constructor(config: ALiSLSParams) {
        try {
            let ALY = require('aliyun-sdk')
            this.SLS = new ALY.SLS({
                accessKeyId: config.accessKeyId, // 步骤2获取的密钥
                secretAccessKey: config.secretAccessKey, // 步骤2获取的密钥值
                endpoint: config.endpoint,
                apiVersion: config.apiVersion
            })
            this.open = true;
        }
        catch (e) {
            // throw Error("need npm i aliyun-sdk")
            console.error("need: npm i aliyun-sdk")
        }
    }

    async init() {
        if (this.handle) this.handle.stop();
        this.handle = Util.setInterval(this.update.bind(this), 2000);
        return true
    }

    public mkdirsSync(dirpath: string) {
        if (!existsSync(dirpath)) {
            mkdirSync(dirpath, { recursive: true })
        }
        return true;
    }

    private putLogs(info: any) {
        return new Promise((r, j) => {
            this.SLS.putLogs(info, function (error: any, data: any) {
                if (error) {
                    j(error)
                }
                else {
                    r(data)
                }
            })

        })
    }

    private async update() {
        if (!this.open) {
            this._catch.clear();
            return;
        }
        // this.mkdirsSync(this.path);

        let keys = this._catch.keys;
        for (let j = 0; j < keys.length; j++) {
            let cache = this._catch.get(keys[j]);
            let logGroup: any = {
                logs: [],
                topic: keys[j]
            }
            for (let i = 0; i < cache.length; i++) logGroup.logs.push(cache[i]);
            if (logGroup.logs.length > 0) {
                // 暂时都投递算了
                this.putLogs({
                    projectName: "mx-hudong",
                    logStoreName: "taobaoplt",
                    logGroup
                }).catch(function (e) {
                    console.log("logs error", e)
                })
            }
        }

        this._catch.clear();
        return;
    }

    logEvent(uid: string, event_name: string, obj: any) {
        let s = {
            time: Math.floor(LocalDate.now() / 1000),
            contents: [{ key: "#account_id", value: uid }, { key: "#event_name", value: event_name }]
        }

        for (let key in obj) {
            s.contents.push({
                key: key,
                value: (obj[key] || "").toString()
            })
        }

        this._catch.add(event_name, s);
    }

    logStatic(uid: string, eventType: string, obj: Object) {
        // let account_id = uid.toString();
        // let s = {
        //     "#account_id": account_id,
        //     // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
        //     "#type": eventType.toString(),
        //     // "#ip": "192.168.171.111",
        //     "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
        //     "properties": obj
        // }

        // this._catch.add('_static_', s);
        return;
    }

    logApi(api: string, method: string, uid: string, succ: boolean, consumeTime: number, reqID: string, param: string, response: string) {
        let event_name = "api";
        let s = {
            "#account_id": (uid || "").toString(),
            // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
            "#type": 'track',
            // "#ip": "192.168.171.111",
            // "#time": "2017-12-18 14:37:28.527",
            "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
            "#event_name": event_name,
            "properties": {
                'api_category': api,
                'api_method': method,
                'is_success': succ ? 1 : 0, // 1成功 0失败
                'consume_time': consumeTime, // 耗时 15毫秒
                'user_from': (uid || "null").toString(),
                'user_identify': (reqID || "null").toString(), // 记录标识  可以是订单号
                'api_response': response,
                'api_param': param,
            }
        }

        this._catch.add(event_name, s);
    }
}